<template>
  <div class="app-container">
    <div class="flex items-center justify-between">
      <div class="flex items-center gap-2">
        <el-text tag="b">基本信息</el-text>
        <el-text v-if="houseInfo.description" type="info" size="small">
          {{ houseInfo.description }}
        </el-text>
      </div>
    </div>
    <hr>
    </hr>
    <el-form ref="leasecontractRef" :model="form" label-width="110px" :rules="rules">

      <el-form-item hidden label="租户ID" v-if="false" prop="tenantId">
        <el-input v-model="form.tenantId" />
      </el-form-item>

      <el-row>
        <el-col :span="6" v-if="!isNew">
          <el-form-item label="合同编号" prop="leaseContractNumber">
            <el-text>{{ form.leaseContractNumber }}</el-text>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="托管房源" prop="homeownersContractId">
            <HouseSelector v-model="form.homeownersContractId" placeholder="请选择托管房源" :disabled="isReadOnly" />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="合同开始时间" prop="contractStartTime" label-width="110px">
            <el-date-picker clearable v-model="form.contractStartTime" type="date" value-format="YYYY-MM-DD"
              placeholder="请选择合同开始时间" :disabled="isReadOnly">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="合同结束时间" prop="contractEndTime" label-width="110px">
            <el-date-picker clearable v-model="form.contractEndTime" type="date" value-format="YYYY-MM-DD"
              placeholder="请选择合同结束时间" :disabled="isReadOnly">
            </el-date-picker>
          </el-form-item>
        </el-col>

      </el-row>



      <el-row>
        <el-col :span="6">
          <el-form-item label="租户姓名" prop="tenantName">
            <el-input v-model="form.tenantName" v-trim placeholder="请输入租户姓名" :disabled="isReadOnly" />

          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="form.phone" v-trim placeholder="请输入联系电话" :disabled="isReadOnly" />
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="!isNew">
          <el-form-item label="合同状态" prop="contractStatus">
            <el-text>{{ contractStatusText }}</el-text>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="是否启用账号" prop="isUse">
            <el-switch v-model="form.isUse" :active-value="'1'" :inactive-value="'0'" inline-prompt active-text="开"
              inactive-text="关" :disabled="isReadOnly" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="6">
          <el-form-item label="签署日期" prop="signingDate">
            <el-date-picker clearable v-model="form.signingDate" type="date" value-format="YYYY-MM-DD"
              placeholder="请选择签署日期" :disabled="isReadOnly">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="身份证" prop="tenantIdentity">
            <el-input v-model="form.tenantIdentity" v-trim placeholder="请输入身份证" :disabled="isReadOnly" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="押金描述" prop="depositDescription">
            <el-input v-model="form.depositDescription" v-trim type="textarea" placeholder="请输入押金描述" :disabled="isReadOnly" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="说明" prop="contractDescribe">
            <el-input v-model="form.contractDescribe" v-trim type="textarea" placeholder="请输入内容" :disabled="isReadOnly" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 合同文件部分 -->
      <el-form-item label="" class="mb-0">
        <el-text type="danger" size="small">租赁合同信息仅租客账号可查看</el-text>
      </el-form-item>
      <el-row>
        <el-col :span="24">
          <el-form-item label="合同文件">
            <div class="contract-files-section">
              <div class="flex gap-6" style="align-items: flex-start !important">
                <div class="flex-1" style="
                      display: flex;
                      flex-direction: column;
                      align-items: flex-start;
                    ">
                  <file-upload v-model="form.identityFileVo" :fileType="['png', 'jpg', 'jpeg']" :limit="1"
                    :showDownload="true" :showTip="false" title="身份证正面" :disabled="isReadOnly" />
                </div>
                <div class="flex-1" style="
                      display: flex;
                      flex-direction: column;
                      align-items: flex-start;
                    ">
                  <file-upload v-model="form.identityFileTwoVo" :fileType="['png', 'jpg', 'jpeg']" :limit="1"
                    :showDownload="true" :showTip="false" title="身份证反面" :disabled="isReadOnly" />
                </div>
                <div class="flex-1" style="
                      display: flex;
                      flex-direction: column;
                      align-items: flex-start;
                    ">
                  <file-upload v-model="form.tenantFurnitureFileVo"
                    :fileType="['pdf', 'doc', 'docx', 'png', 'jpg', 'jpeg']" :limit="1" :showDownload="true"
                    :showTip="false" title="家具" :disabled="isReadOnly" />
                </div>
                <div class="flex-1" style="
                      display: flex;
                      flex-direction: column;
                      align-items: flex-start;
                    ">
                  <file-upload v-model="form.tenantManagementFeeFileVo"
                    :fileType="['pdf', 'doc', 'docx', 'png', 'jpg', 'jpeg']" :limit="1" :showDownload="true"
                    :showTip="false" title="管理费" :disabled="isReadOnly" />
                </div>
                <div class="flex-1" style="
                      display: flex;
                      flex-direction: column;
                      align-items: flex-start;
                    ">
                  <file-upload v-model="form.tenantHandoverFileVo"
                    :fileType="['pdf', 'doc', 'docx', 'png', 'jpg', 'jpeg']" :limit="1" :showDownload="true"
                    :showTip="false" title="交接书" :disabled="isReadOnly" />
                </div>
                <div class="flex-1" style="
                      display: flex;
                      flex-direction: column;
                      align-items: flex-start;
                    ">
                  <file-upload v-model="form.tenantContractFileVo"
                    :fileType="['pdf', 'doc', 'docx', 'png', 'jpg', 'jpeg']" :limit="1" :showDownload="true"
                    :showTip="false" title="租房合同" :disabled="isReadOnly" />
                </div>
              </div>
            </div>
          </el-form-item>
        </el-col>
      </el-row>


      <div class="flex items-center justify-between">
        <div>
          <el-text tag="b" class="mr-2">费用信息</el-text>
          <el-text type="danger" size="small">租金及管理费描述：租金3000-3500/月，租客管理费200/月，业主管理费150/月，包含日常维护和管理服务</el-text>
        </div>
      </div>
      <hr>
      </hr>

      <!-- 三个信息卡片 -->
      <el-row :gutter="16" class="mb-6">
        <!-- 基本信息卡片 -->
        <el-col :span="8">
          <div class="bg-blue-50 rounded-lg p-4 border border-gray-200 h-full flex flex-col">
            <div class="text-base font-semibold text-gray-800 mb-3">基本信息</div>
            <div class="space-y-2 flex-1">
              <div class="text-sm">
                <span class="text-gray-600">合同期：</span>
                <span class="text-red-500 font-medium ml-2">
                  {{ form.contractStartTime }} - {{ form.contractEndTime }}
                  <span class="text-gray-500">({{ accountSummary.contractDuration }}天)</span>
                </span>
              </div>
              <div class="text-sm">
                <span class="text-gray-600">账期数量：</span>
                <span class="text-gray-800 ml-2">共{{ accountSummary.totalPeriods }}个账期</span>
              </div>
            </div>
          </div>
        </el-col>

        <!-- 费用汇总卡片 -->
        <el-col :span="8">
          <div class="bg-blue-50 rounded-lg p-4 border border-gray-200 h-full flex flex-col">
            <div class="text-base font-semibold text-gray-800 mb-3">费用汇总</div>
            <div class="space-y-2 flex-1">
              <div class="text-sm">
                <span class="text-gray-600">租客总支付：</span>
                <span class="text-red-500 font-medium ml-2">¥{{ accountSummary.tenantTotalPayment.toLocaleString() }}元</span>
              </div>
              <div class="text-sm">
                <span class="text-gray-600">业主总收入：</span>
                <span class="text-red-500 font-medium ml-2">¥{{ accountSummary.ownerTotalIncome.toLocaleString() }}元</span>
              </div>
              <div class="text-sm">
                <span class="text-gray-600">管理费总收入：</span>
                <span class="text-red-500 font-medium ml-2">¥{{ accountSummary.managementFeeTotal.toLocaleString() }}元</span>
              </div>
            </div>
          </div>
        </el-col>

        <!-- 账期关键信息卡片 -->
        <el-col :span="8">
          <div class="bg-blue-50 rounded-lg p-4 border border-blue-200 h-full flex flex-col">
            <div class="text-base font-semibold text-gray-800 mb-3">账期关键信息</div>
            <div class="space-y-2 flex-1">
              <div class="text-sm">
                <span class="text-gray-600">首期：</span>
                <span class="text-red-500 font-medium ml-2">
                  {{ accountSummary.firstPeriod?.totalDay || 0 }}天, 
                  租金¥{{ (accountSummary.firstPeriod?.tenantRent || 0).toLocaleString() }}元
                </span>
              </div>
              <div class="text-sm">
                <span class="text-gray-600">末期：</span>
                <span class="text-red-500 font-medium ml-2">
                  {{ accountSummary.lastPeriod?.totalDay || 0 }}天, 
                  租金¥{{ (accountSummary.lastPeriod?.tenantRent || 0).toLocaleString() }}元
                </span>
              </div>
              <div class="text-sm">
                <span class="text-gray-600">租客管理费总计：</span>
                <span class="text-red-500 font-medium ml-2">¥{{ accountSummary.tenantManagementFeeTotal.toLocaleString() }}元</span>
              </div>
              <div class="text-sm">
                <span class="text-gray-600">业主管理费总计：</span>
                <span class="text-red-500 font-medium ml-2">¥{{ accountSummary.ownerManagementFeeTotal.toLocaleString() }}元</span>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>


      <el-row>
        <el-col :span="24">
          <div>
            <accountPeriod :leaseContractId="route.params.id" :disabled="isReadOnly" ref="leaseaccperListRef" />
          </div>
        </el-col>
      </el-row>

      <br /></br>
      <el-row>
        <el-col :span="24" style="display: flex; justify-content: flex-end; margin-bottom: 20px;">
          <el-popconfirm title="确认删除草稿？" @confirm="deleteDraft">
            <template #reference>
              <el-button type="danger" v-hasPermi="['fang:leasecontract:deletedraft']" v-if="form.contractStatus == 0">删除草稿</el-button>
            </template>
          </el-popconfirm>
          <el-button @click="saveDraft" type="primary" v-hasPermi="['fang:leasecontract:savedraft']" v-if="!form.id || form.contractStatus == 0">保存草稿</el-button>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24" style="display: flex; justify-content: flex-end">
          <!-- <el-button @click="cancel">取消</el-button> -->
          <el-button @click="renewalReminder" type="warning" v-hasPermi="['fang:leasecontract:reminder']" v-if="form.id && form.contractStatus != 0">发送续期提醒</el-button>
          <el-popconfirm title="确认终止合同？" @confirm="terminateContract">
            <template #reference>
              <el-button type="danger" v-hasPermi="['fang:leasecontract:terminatecontract']" v-if="form.id && form.contractStatus != 0">终止合同</el-button>
            </template>
          </el-popconfirm>
          <el-button @click="saveContract" type="primary" v-hasPermi="['fang:leasecontract:savecontract']">保存合同</el-button>
        </el-col>
      </el-row>
    </el-form>

    <!-- 续期提醒确认对话框 -->
    <el-dialog v-model="reminderVisible" title="续期提醒" width="500px">
      <div class="whitespace-pre-wrap">{{ reminderContent }}</div>
      <template #footer>
        <el-button @click="reminderVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmReminder">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Leaseaccper">
import {
  listLeasecontract, getLeasecontract, delLeasecontract, addLeasecontract,
  updateLeasecontract, saveDraftLeasecontract, saveContractLeasecontract, deleteDraftLeasecontract,
  getLeasecontractReminder, confirmLeasecontractReminder
} from "@/api/fang/leasecontract"
import { getHomeownersContract } from "@/api/fang/homeowners"
import { LEASE_CONTRACT_STATUS, LEASE_CONTRACT_STATUS_TEXT } from "@/utils/enums"
import { getFileObj } from "@/utils/tools"
import modal from "@/plugins/modal"
import tab from "@/plugins/tab"
import auth from "@/plugins/auth"

import accountPeriod from './accountPeriod.vue'
import HouseSelector from "@/components/HouseSelector/index.vue"

// 文件字段配置
const FILE_FIELDS = [
  { vo: 'identityFileVo', file: 'identityFile', url: 'identityFileUrl' },
  { vo: 'identityFileTwoVo', file: 'identityFileTwo', url: 'identityFileTwoUrl' },
  { vo: 'tenantFurnitureFileVo', file: 'tenantFurnitureFile', url: 'tenantFurnitureFileUrl' },
  { vo: 'tenantManagementFeeFileVo', file: 'tenantManagementFeeFile', url: 'tenantManagementFeeFileUrl' },
  { vo: 'tenantHandoverFileVo', file: 'tenantHandoverFile', url: 'tenantHandoverFileUrl' },
  { vo: 'tenantContractFileVo', file: 'tenantContractFile', url: 'tenantContractFileUrl' }
]

// 转换文件数据为接口格式
function convertFilesToApiFormat(formData) {
  const result = { ...formData }

  FILE_FIELDS.forEach(({ vo, file, url }) => {
    const fileVo = formData[vo]?.[0] ?? {}
    result[file] = fileVo.id
    result[url] = fileVo.filePath || fileVo.url
    result[vo] = fileVo.id ? {
      id: fileVo.id,
      filePath: fileVo.filePath || fileVo.url,
      originalName: fileVo.originalName || fileVo.name,
    } : undefined
  })

  return result
}

// 转换接口数据为组件格式
function convertApiToComponentFormat(formData) {
  const result = { ...formData }

  FILE_FIELDS.forEach(({ vo }) => {
    result[vo] = getFileObj(formData[vo])
  })

  return result
}

const route = useRoute()

const leaseaccperListRef = ref(null)
const leasecontractRef = ref(null)
const reminderVisible = ref(false)
const reminderContent = ref("")
const reminderData = ref(null)

// 房源信息
const houseInfo = reactive({
  address: '',
  houseArea: '',
  houseType: '',
  description: '' // 格式：地址 户型 · 面积㎡
})

const data = reactive({
  form: {},
  queryParams: {}
})

const { form } = toRefs(data)

// 判断是否是新增模式
const isNew = computed(() => {
  const id = route.params && route.params.id
  return !id || id <= 0
})

// 只读模式：没有新增或编辑权限时，表单只读
const isReadOnly = computed(() => {
  // 如果没有保存草稿权限且没有保存合同权限，则为只读
  return !auth.hasPermi('fang:leasecontract:savedraft') && 
         !auth.hasPermi('fang:leasecontract:savecontract')
})

// 合同状态文本
const contractStatusText = computed(() => {
  const status = form.value.contractStatus
  return LEASE_CONTRACT_STATUS_TEXT[status] || '未知状态'
})

// 计算账期汇总数据
const accountSummary = computed(() => {
  const accountList = leaseaccperListRef.value?.leaseaccperList || []
  
  if (accountList.length === 0) {
    return {
      totalPeriods: 0,
      contractDuration: 0,
      tenantTotalPayment: 0,
      ownerTotalIncome: 0,
      managementFeeTotal: 0,
      firstPeriod: null,
      lastPeriod: null,
      tenantManagementFeeTotal: 0,
      ownerManagementFeeTotal: 0
    }
  }

  // 计算合同总天数
  let contractDuration = 0
  if (form.value.contractStartTime && form.value.contractEndTime) {
    const contractStart = new Date(form.value.contractStartTime)
    const contractEnd = new Date(form.value.contractEndTime)
    contractDuration = Math.ceil((contractEnd - contractStart) / (1000 * 60 * 60 * 24))
  }

  // 计算各项汇总
  const tenantTotalPayment = accountList.reduce((sum, item) => sum + (Number(item.tenantRent) || 0), 0)
  const tenantManagementFeeTotal = accountList.reduce((sum, item) => sum + (Number(item.tenantManagementFee) || 0), 0)
  const ownerManagementFeeTotal = accountList.reduce((sum, item) => sum + (Number(item.homeownersManagementFee) || 0), 0)
  const managementFeeTotal = tenantManagementFeeTotal + ownerManagementFeeTotal
  const ownerTotalIncome = tenantTotalPayment - managementFeeTotal

  // 首期和末期信息
  const firstPeriod = accountList[0] || null
  const lastPeriod = accountList[accountList.length - 1] || null

  return {
    totalPeriods: accountList.length,
    contractDuration,
    tenantTotalPayment,
    ownerTotalIncome,
    managementFeeTotal,
    firstPeriod,
    lastPeriod,
    tenantManagementFeeTotal,
    ownerManagementFeeTotal
  }
})

// 监听账期数据变化，确保卡片数据实时更新
watch(() => leaseaccperListRef.value?.leaseaccperList, () => {
  // 触发计算属性重新计算
}, { deep: true })

// 获取房源详情
async function loadHouseInfo(contractId) {
  if (!contractId) {
    // 清空房源信息
    houseInfo.address = ''
    houseInfo.houseArea = ''
    houseInfo.houseType = ''
    houseInfo.description = ''
    return
  }
  
  try {
    const response = await getHomeownersContract(contractId)
    const data = response.data || {}
    
    houseInfo.address = data.address || ''
    houseInfo.houseArea = data.houseArea || ''
    // 尝试多种可能的户型字段名
    // houseInfo.houseType = data.houseType || data.houseTypeDescription || data.roomType || data.houseDescribe || ''
    houseInfo.houseType = ''
    
    // 格式化描述信息：地址 户型 · 面积㎡
    // 示例：南山区华润城3栋1101 2室1厅1卫 · 85㎡
    const parts = []
    
    // 地址部分
    if (houseInfo.address) {
      parts.push(houseInfo.address)
    }
    
    // 户型部分（如果有）
    if (houseInfo.houseType) {
      parts.push(houseInfo.houseType)
    }
    
    // 面积部分
    if (houseInfo.houseArea) {
      parts.push(`${houseInfo.houseArea}㎡`)
    }
    
    // 组合：如果有地址和户型，格式为"地址 户型 · 面积㎡"
    // 如果只有地址，格式为"地址 · 面积㎡"
    // 如果只有面积，格式为"面积㎡"
    if (parts.length === 0) {
      houseInfo.description = ''
    } else if (parts.length === 1) {
      houseInfo.description = parts[0]
    } else if (parts.length === 2) {
      // 两个部分：如果是地址和面积，用 · 分隔；如果是地址和户型，用空格分隔
      if (parts[1].endsWith('㎡')) {
        houseInfo.description = `${parts[0]} · ${parts[1]}`
      } else {
        houseInfo.description = `${parts[0]} ${parts[1]}`
      }
    } else {
      // 三个部分：地址 户型 · 面积㎡
      houseInfo.description = `${parts[0]} ${parts[1]} · ${parts[2]}`
    }
  } catch (error) {
    console.error('获取房源详情失败:', error)
    houseInfo.description = ''
  }
}

// 监听房源ID变化，实时获取房源信息
watch(() => form.value.homeownersContractId, (newVal, oldVal) => {
  if (newVal && newVal !== oldVal) {
    console.log("房源ID变化，重新加载房源信息:", newVal)
    loadHouseInfo(newVal)
  } else if (!newVal) {
    houseInfo.description = ''
  }
}, { immediate: false })



// 合同状态选项
const contractStatusDic = [
  { val: LEASE_CONTRACT_STATUS.DRAFT, label: LEASE_CONTRACT_STATUS_TEXT[LEASE_CONTRACT_STATUS.DRAFT] },
  { val: LEASE_CONTRACT_STATUS.VALID, label: LEASE_CONTRACT_STATUS_TEXT[LEASE_CONTRACT_STATUS.VALID] },
  { val: LEASE_CONTRACT_STATUS.INVALID, label: LEASE_CONTRACT_STATUS_TEXT[LEASE_CONTRACT_STATUS.INVALID] }
]


// 表单重置
function reset() {
  form.value = {
    id: null,
    tenantId: null,
    homeownersContractId: null,
    tenantName: null,
    leaseContractNumber: null,
    phone: null,
    tenantIdentity: null,
    contractDescribe: null,
    contractStatus: null,
    contractStartTime: null,
    contractEndTime: null,
    depositDescription: null,
    signingDate: null,
    isUse: '0',
    identityFile: null,
    identityFileUrl: null,
    identityFileVo: [],
    identityFileTwo: null,
    identityFileTwoUrl: null,
    identityFileTwoVo: [],
    tenantFurnitureFile: null,
    tenantFurnitureFileUrl: null,
    tenantFurnitureFileVo: [],
    tenantManagementFeeFile: null,
    tenantManagementFeeFileUrl: null,
    tenantManagementFeeFileVo: [],
    tenantContractFile: null,
    tenantContractFileUrl: null,
    tenantContractFileVo: [],
    tenantHandoverFile: null,
    tenantHandoverFileUrl: null,
    tenantHandoverFileVo: [],
    createBy: null,
    updateBy: null,
    createTime: null,
    updateTime: null
  }
  leasecontractRef.value?.resetFields()
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}


/** 存草稿**/
function saveDraft() {
  leasecontractRef.value?.validate(valid => {
    if (valid) {
      // 使用 getSubmitData 方法获取转换后的账期数据
      form.value.leaseaccperList = leaseaccperListRef.value?.getSubmitData() || []
      const submitData = convertFilesToApiFormat(form.value)

      saveDraftLeasecontract(submitData).then(response => {
        form.value = convertApiToComponentFormat(response.data)
        modal.msgSuccess("保存成功")
        
        // 如果是新增模式，保存草稿后跳转到详情页
        if (isNew.value && form.value.id) {
          tab.closeOpenPage({ path: `/fang/leasecontract/${form.value.id}` })
        } else {
          // 编辑模式下只更新页面标题
          const obj = Object.assign({}, route, { title: "租赁合同详情" + form.value.leaseContractNumber })
          tab.updatePage(obj);
        }
      })
    }
  })
}
/** 删除草稿**/
function deleteDraft() {
  const id = form.value?.id || route.params?.id
  if (!id) {
    modal.msgError("未找到草稿ID，无法删除")
    return
  }
  deleteDraftLeasecontract(id).then(() => {
    modal.msgSuccess("删除成功")
    tab.closeOpenPage({ path: '/fang/leasecontracts' })
  })
}
/** 保存合同**/
function saveContract() {
  leasecontractRef.value?.validate(valid => {
    if (valid) {
      // 使用 getSubmitData 方法获取转换后的账期数据
      form.value.leaseaccperList = leaseaccperListRef.value?.getSubmitData() || []
      const submitData = convertFilesToApiFormat(form.value)
      
      // 判断是否是新增
      const isNew = !form.value.id

      saveContractLeasecontract(submitData).then(response => {
        form.value = convertApiToComponentFormat(response.data)
        const obj = Object.assign({}, route, { title: "租赁合同详情" + form.value.leaseContractNumber })
        tab.updatePage(obj);
        
        if (isNew) {
          // 新增时关闭当前页面并跳转到列表页
          tab.closeOpenPage({ path: '/fang/leasecontracts' })
        } else {
          // 编辑时只提示成功
          modal.msgSuccess("保存成功")
        }
      })
    }
  })
}
/** 终止合同**/
function terminateContract() {
  open.value = true
}
/**一键下载全部合同 **/
function downloadContract() {
  open.value = true
}
/** 发送续期提醒**/
function renewalReminder() {
  if (!form.value.id) return
  getLeasecontractReminder(form.value.id)
    .then((response) => {
      reminderData.value = response.data
      reminderContent.value = response.data.orgMessageContent || ""
      reminderVisible.value = true
    })
    .catch(() => {
      // 错误处理已在 request 拦截器中统一处理
    })
}

function handleConfirmReminder() {
  if (!reminderData.value || !form.value.id) return
  const data = {
    contractUrl: reminderData.value.contractUrl,
    homeownerContractId: form.value.homeownersContractId || 0,
    leaseContractId: form.value.id,
    orgMessageContent: reminderData.value.orgMessageContent,
  }
  confirmLeasecontractReminder(data)
    .then(() => {
      modal.msgSuccess("已发送提醒")
      reminderVisible.value = false
      reminderData.value = null
      reminderContent.value = ""
    })
    .catch(() => {
      // 错误处理已在 request 拦截器中统一处理
    })
}



/** 提交按钮 */
function submitForm() {
  leasecontractRef.value?.validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateLeasecontract(form.value).then(response => {
          modal.msgSuccess("修改成功")
          open.value = true

        })
      } else {
        addLeasecontract(form.value).then(response => {
          modal.msgSuccess("新增成功")
          open.value = true

        })
      }
    }
  })
}

function initdata() {
  console.log("initdata:")
  const id = route.params && route.params.id

  if (id > 0) {
    console.log("id=:" + id)
    getLeasecontract(id).then(response => {
      const rawData = response.data || {}
      form.value = convertApiToComponentFormat(rawData)
      form.value.contractStatus = rawData.contractStatus
      
      // 初始化时如果有房源ID，加载房源信息
      // 优先从原始响应数据中获取，如果转换后的数据有值也使用
      const homeownersContractId = rawData.homeownersContractId || form.value.homeownersContractId
      
      console.log("原始数据 homeownersContractId:", rawData.homeownersContractId)
      console.log("转换后 form.value.homeownersContractId:", form.value.homeownersContractId)
      console.log("最终使用的 homeownersContractId:", homeownersContractId)
      
      if (homeownersContractId) {
        // 使用 nextTick 确保数据已经更新到 form 中
        nextTick(() => {
          console.log("开始加载房源信息, homeownersContractId:", homeownersContractId)
          loadHouseInfo(homeownersContractId)
        })
      } else {
        console.warn("未找到房源ID，无法加载房源信息")
      }
    }).catch(error => {
      console.error('获取合同详情失败:', error)
    })
  } else {
    console.log("homeownersContractId11:")
    console.log("homeownersContractId:" + form.homeownersContractId)
    reset()
  }
}

initdata()

</script>

<style scoped>
.contract-files-section .flex {
  gap: 20px;
}

.contract-files-section .flex-1 {
  min-width: 120px;
}
</style>
